package com.fa.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
@Configuration
public class DataSourceConfig {
    private final Map<Object, Object> dataSourceMap = new HashMap<>(); // 使用 Object 类型的 Map

    @Bean
    @ConfigurationProperties("spring.datasource.primary")
    public DataSourceProperties primaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DynamicDataSource dataSource(DataSourceProperties primaryDataSourceProperties) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();

        HikariDataSource primaryDataSource = primaryDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
        dataSourceMap.put("default", primaryDataSource);

        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(primaryDataSource);

        return dynamicDataSource;
    }

    @Autowired
    private DynamicDataSource dynamicDataSource; // 注入 DynamicDataSource

    public void addDataSource(String tenantId, String url, String username, String password) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSourceMap.put(tenantId, dataSource);
        updateDynamicDataSource();
    }

    public void removeDataSource(String tenantId) {
        dataSourceMap.remove(tenantId);
        updateDynamicDataSource();
    }

    private void updateDynamicDataSource() {
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.afterPropertiesSet();
    }
}
